package com.xiejun.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class AioClient {
    private AsynchronousSocketChannel clientChannel;

    public void connect(String host, int port) throws IOException, InterruptedException {
        clientChannel = AsynchronousSocketChannel.open();
        Future<Void> future = clientChannel.connect(new InetSocketAddress(host, port));
        try {
            future.get(); // 等待连接完成
        } catch (ExecutionException e) {
            throw new IOException("连接失败", e.getCause());
        }
        System.out.println("Connected to server at " + host + ":" + port);
    }

    public void sendMessage(String message) {
        ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
        clientChannel.write(buffer, buffer, new WriteHandler());
    }

    private class WriteHandler implements CompletionHandler<Integer, ByteBuffer> {
        @Override
        public void completed(Integer result, ByteBuffer attachment) {
            if (attachment.hasRemaining()) {
                clientChannel.write(attachment, attachment, this);
            } else {
                // 读取服务端响应
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                clientChannel.read(readBuffer, readBuffer, new ReadHandler());
            }
        }

        @Override
        public void failed(Throwable exc, ByteBuffer attachment) {
            exc.printStackTrace();
        }
    }

    private class ReadHandler implements CompletionHandler<Integer, ByteBuffer> {
        @Override
        public void completed(Integer result, ByteBuffer attachment) {
            if (result > 0) {
                attachment.flip();
                byte[] bytes = new byte[attachment.remaining()];
                attachment.get(bytes);
                String response = new String(bytes);
                System.out.println("Received from server: " + response);
            }
        }

        @Override
        public void failed(Throwable exc, ByteBuffer attachment) {
            exc.printStackTrace();
        }
    }

    public static void main(String[] args) {
        AioClient client = new AioClient();
        try {
            client.connect("localhost", 9001);
            
            Scanner scanner = new Scanner(System.in);
            System.out.println("Enter message (type 'quit' to exit):");
            
            String input;
            while (!(input = scanner.nextLine()).equals("quit")) {
                client.sendMessage(input);
                Thread.sleep(1000); // 等待服务端响应
            }
            
            scanner.close();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}